package server;
import java.io.*;
import java.util.Arrays;

import msgs.*;
/**
 * Updates/gets profiles for the clients
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class ProfileWorker extends Thread implements TTConstants {
	private ProfileMsg pmsg;
	
	public ProfileWorker(ClientMsg c) {
		this.pmsg = (ProfileMsg) c;
	}
	
	public void run() {
		// check for validity right off the bat
		if (!(Arrays.equals(pmsg.getClientKey(), TTServer.connTable.get(pmsg.getName()).getClientKey()))) {
			pmsg.setResponse(Responses.DENY);
			ClientSender.outQ.add((ClientMsg)pmsg);
			return;
		}
		
		switch(pmsg.getAction()) {
		case PROFILE_UPDATE:
			try {
				// cool, set their profile
				File dir = new File("data/profiles");
				if (!(dir.exists())) dir.mkdir();
				File pfile = new File("data/profiles/" + pmsg.getName());
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(pfile));
				oos.writeObject(pmsg.getProfile());
				oos.flush();
				oos.close();
				pmsg.setResponse(TTConstants.Responses.OK);
			}
			catch (Exception e) {}
			ClientSender.outQ.add((ClientMsg) pmsg);
			return;
		case PROFILE_REQUEST:
			// check to see if they're blocked
			if (TTServer.blockList.containsKey(pmsg.getWantsProfile())) {
				if (TTServer.blockList.get(pmsg.getWantsProfile()).contains(pmsg.getName())) {
					pmsg.setResponse(Responses.DENY);
					ClientSender.outQ.add((ClientMsg) pmsg);
					return;
				}
			}
			
			// else, we're going to go ahead and process their profile request.
			try {
				File f = new File("data/profiles/" + pmsg.getWantsProfile());
				if (!(f.exists())) {
					pmsg.setResponse(Responses.OK);
					pmsg.setProfile(null);
				}
				else {
					//read in from disk
					ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
					pmsg.setResponse(Responses.OK);
					System.out.println(pmsg.getResponse());
					pmsg.setProfile((String)ois.readObject());
					System.out.println(pmsg.getProfile());
					ois.close();
				}
			}
			catch (Exception e) { e.printStackTrace(); };
			ClientSender.outQ.add((ClientMsg) pmsg);
			break;
		}
	}
}
